package pack3;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

public class test9 {

    public static double calculatePiWithStaticVariable() {
        int M = 1000000;
        int N = 0;
        Random random = new Random();
        for (int i = 0; i < M; i++) {
            double x = random.nextDouble();
            double y = random.nextDouble();
            if (x * x + y * y <= 1) {
                N++;
            }
        }
        return 4.0 * N / M;
    }


    public static double calculatePiWithMorePoints() {
        int M = 100000000;
        int N = 0;
        Random random = new Random();
        for (int i = 0; i < M; i++) {
            double x = random.nextDouble();
            double y = random.nextDouble();
            if (x * x + y * y <= 1) {
                N++;
            }
        }
        return 4.0 * N / M;
    }


    public static BigDecimal calculateAndFormatPi() {
        int M = 100000000;
        int N = 0;
        Random random = new Random();
        for (int i = 0; i < M; i++) {
            double x = random.nextDouble();
            double y = random.nextDouble();
            if (x * x + y * y <= 1) {
                N++;
            }
        }
        BigDecimal pi = new BigDecimal(4.0 * N / M);
        return pi.setScale(20, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {
        double pi1 = calculatePiWithStaticVariable();
        System.out.println("当M=10^6时，圆周率π约为: " + pi1);

        double pi2 = calculatePiWithMorePoints();
        System.out.println("当M=10^8时，圆周率π约为: " + pi2);

        BigDecimal pi3 = calculateAndFormatPi();
        System.out.println("保存小数点后20位的圆周率π为: " + pi3);
    }
}